package com.bmslz.monitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmslz.monitor.base.util.PasswordUtil;
import com.bmslz.monitor.base.util.StringUtils;
import com.bmslz.monitor.base.config.excep.MyException;
import com.bmslz.monitor.base.dto.UserSaveDto;
import com.bmslz.monitor.base.entity.User;
import com.bmslz.monitor.mapper.UserMapper;
import com.bmslz.monitor.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description: 用户管理
 * @Author: bobo
 * @Date: 2025-08-25
 * @Version: V1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User queryUserByUsername(String userName) {
        return this.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, userName), false);
    }

    @Override
    public void customsSave(UserSaveDto dto) {
        dto.check();
        //有id是修改 没id走新增
        User saveUser = new User();
        saveUser.setUsername(dto.getUsername());
        saveUser.setName(dto.getName());
        saveUser.setRole(dto.getRole());
        saveUser.setOrderCloseTime(dto.getOrderCloseTime());
        if (StringUtils.isEmpty(dto.getId())) {
            if (StringUtils.isEmpty(dto.getPassword())) {
                throw new MyException(500, "密码不能为空");
            }
            String salt = StringUtils.randomGen(8);
            saveUser.setPassword(PasswordUtil.encrypt(dto.getUsername(), dto.getPassword(), salt));
            saveUser.setSalt(salt);
            this.save(saveUser);
        } else {
            User user = baseMapper.selectById(dto.getId());
            if (user == null) {
                throw new MyException(500, "用户不存在");
            }
            if (StringUtils.isNotEmpty(dto.getPassword())) {
                //修改密码
                saveUser.setPassword(PasswordUtil.encrypt(dto.getUsername(), dto.getPassword(), user.getSalt()));
            }
            saveUser.setId(dto.getId());
            this.updateById(saveUser);
        }
    }

    @Override
    public Long total(Date startTime, Date endTime) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
        if (startTime != null) {
            wrapper.ge(User::getCreateTime, startTime);
        }
        if (endTime != null) {
            wrapper.le(User::getCreateTime, endTime);
        }
        return this.count(wrapper);
    }
}
